from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from sqlalchemy.orm import Session

from app.db.session import get_db
from app.crud.crud_post import post_crud
from app.schemas.post import (
    PostCreate, PostUpdate, PostResponse, 
    AIGenerateRequest, AIGenerateResponse
)
from app.services.ai_service import ai_service
from app.services.storage_service import storage_service
from app.services.playwright_service import playwright_service

router = APIRouter()


@router.post("/", response_model=PostResponse)
def create_post(
    post_in: PostCreate,
    db: Session = Depends(get_db)
):
    """创建帖子"""
    post = post_crud.create(db=db, obj_in=post_in)
    return post


@router.get("/", response_model=List[PostResponse])
def get_posts(
    skip: int = 0,
    limit: int = 100,
    status: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取帖子列表"""
    if status is not None:
        posts = post_crud.get_by_status(db=db, status=status, skip=skip, limit=limit)
    else:
        posts = post_crud.get_multi(db=db, skip=skip, limit=limit)
    return posts


@router.get("/{post_id}", response_model=PostResponse)
def get_post(
    post_id: int,
    db: Session = Depends(get_db)
):
    """获取单个帖子"""
    post = post_crud.get(db=db, id=post_id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    return post


@router.put("/{post_id}", response_model=PostResponse)
def update_post(
    post_id: int,
    post_in: PostUpdate,
    db: Session = Depends(get_db)
):
    """更新帖子"""
    post = post_crud.get(db=db, id=post_id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    post = post_crud.update(db=db, db_obj=post, obj_in=post_in)
    return post


@router.delete("/{post_id}")
def delete_post(
    post_id: int,
    db: Session = Depends(get_db)
):
    """删除帖子"""
    post = post_crud.get(db=db, id=post_id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    post_crud.delete(db=db, id=post_id)
    return {"message": "Post deleted successfully"}


@router.post("/generate-content", response_model=AIGenerateResponse)
def generate_content(
    request: AIGenerateRequest
):
    """使用AI生成内容"""
    if not ai_service.is_available():
        raise HTTPException(
            status_code=503, 
            detail="AI service is not available. Please check configuration."
        )
    
    try:
        result = ai_service.generate_post_content(
            topic=request.topic,
            style=request.style
        )
        
        return AIGenerateResponse(
            title=result["title"],
            content=result["content"],
            suggested_tags=result.get("suggested_tags")
        )
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate content: {str(e)}"
        )


@router.post("/generate-and-create", response_model=PostResponse)
def generate_and_create_post(
    request: AIGenerateRequest,
    db: Session = Depends(get_db)
):
    """生成内容并创建帖子"""
    if not ai_service.is_available():
        raise HTTPException(
            status_code=503, 
            detail="AI service is not available. Please check configuration."
        )
    
    try:
        # 生成内容
        result = ai_service.generate_post_content(
            topic=request.topic,
            style=request.style
        )
        
        # 创建帖子
        post_data = PostCreate(
            title=result["title"],
            content=result["content"],
            tags=result.get("suggested_tags")
        )
        
        post = post_crud.create(db=db, obj_in=post_data)
        return post
    
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to generate and create post: {str(e)}"
        )


@router.post("/{post_id}/upload-images")
async def upload_images(
    post_id: int,
    files: List[UploadFile] = File(...),
    db: Session = Depends(get_db)
):
    """为帖子上传图片"""
    # 检查帖子是否存在
    post = post_crud.get(db=db, id=post_id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    if not storage_service.is_available():
        raise HTTPException(
            status_code=503,
            detail="Storage service is not available. Please check configuration."
        )
    
    # 检查文件数量
    if len(files) > 9:
        raise HTTPException(
            status_code=400,
            detail="Too many files. Maximum 9 images allowed."
        )
    
    uploaded_urls = []
    
    try:
        for i, file in enumerate(files):
            # 检查文件类型
            if not file.content_type.startswith('image/'):
                raise HTTPException(
                    status_code=400,
                    detail=f"File {file.filename} is not an image"
                )
            
            # 生成对象存储路径
            file_extension = file.filename.split('.')[-1] if '.' in file.filename else 'jpg'
            object_name = f"posts/{post_id}/image_{i}_{file.filename}"
            
            # 保存临时文件
            import tempfile
            import os
            
            with tempfile.NamedTemporaryFile(delete=False, suffix=f".{file_extension}") as temp_file:
                content = await file.read()
                temp_file.write(content)
                temp_file_path = temp_file.name
            
            try:
                # 上传到对象存储
                url = storage_service.upload_file(
                    file_path=temp_file_path,
                    object_name=object_name,
                    content_type=file.content_type
                )
                
                if url:
                    uploaded_urls.append(url)
                else:
                    raise HTTPException(
                        status_code=500,
                        detail=f"Failed to upload {file.filename}"
                    )
            
            finally:
                # 清理临时文件
                if os.path.exists(temp_file_path):
                    os.unlink(temp_file_path)
        
        # 更新帖子的图片列表
        current_images = post.images or []
        updated_images = current_images + uploaded_urls
        
        post_update = PostUpdate(images=updated_images)
        updated_post = post_crud.update(db=db, db_obj=post, obj_in=post_update)
        
        return {
            "message": f"Successfully uploaded {len(uploaded_urls)} images",
            "uploaded_urls": uploaded_urls,
            "total_images": len(updated_images)
        }
    
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to upload images: {str(e)}"
        )


@router.post("/{post_id}/validate")
def validate_post(
    post_id: int,
    db: Session = Depends(get_db)
):
    """验证帖子是否可以发布"""
    post = post_crud.get(db=db, id=post_id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    post_data = {
        "title": post.title,
        "content": post.content,
        "images": post.images or [],
        "tags": post.tags or ""
    }
    
    validation_result = playwright_service.validate_post_data(post_data)
    
    return {
        "post_id": post_id,
        "validation_result": validation_result
    }


@router.patch("/{post_id}/status")
def update_post_status(
    post_id: int,
    status: int,
    error_message: Optional[str] = None,
    db: Session = Depends(get_db)
):
    """更新帖子状态"""
    post = post_crud.get(db=db, id=post_id)
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    # 验证状态值
    valid_statuses = [0, 1, 2, 3]  # 0-草稿, 1-待发布, 2-已发布, 3-发布失败
    if status not in valid_statuses:
        raise HTTPException(
            status_code=400,
            detail=f"Invalid status. Must be one of {valid_statuses}"
        )
    
    updated_post = post_crud.update_status(
        db=db,
        post_id=post_id,
        status=status,
        error_message=error_message
    )
    
    return {
        "message": "Status updated successfully",
        "post_id": post_id,
        "new_status": status
    }